package com.javadroid.dao;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import com.javadroid.model.DicionarioDeDados;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

public class FileProcess {
	
	private Context context;
	private byte[] image;
	
	public FileProcess(Context context) {
		this.context = context;
	}
	
	
	public void copyAssets() {
	    AssetManager assetManager = context.getAssets();
	    String[] files = null;
	    try {
	        files = assetManager.list("");
	    } catch (IOException e) {
	        Log.e("tag", "Failed to get asset file list.", e);
	    }
	    for(String filename : files) {
	        InputStream in = null;
	        OutputStream out = null;
	        try {
				if (!filename.startsWith("images")
						&& !filename.startsWith("sounds")
						&& !filename.startsWith("webkit")) {

					in = assetManager.open(filename);
					File outFile = new File(context.getExternalFilesDir(null),filename);
					out = new FileOutputStream(outFile);
					copyFile(in, out);
					in.close();
					in = null;
					out.flush();
					out.close();
					out = null;
				}
	        } catch(IOException e) {
	            Log.e("tag", "Failed to copy asset file: " + filename, e);
	        }       
	    }
	}
	private void copyFile(InputStream in, OutputStream out) throws IOException {
	    byte[] buffer = new byte[1024];
	    int read;
	    while((read = in.read(buffer)) != -1){
	      out.write(buffer, 0, read);
	    }
	}
	
	public void montaImagem(final String nomeArquivo){
		
		new Thread() {
			public void run() {
				try {
					File outFile = new File(context.getExternalFilesDir(null),	nomeArquivo);
					FileOutputStream fos = new FileOutputStream(outFile);
					fos.write(imageByter(context, nomeArquivo));
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	
	
	private byte[] imageByter(Context ctx, final String strurl) {

		try {
			URL url = new URL(DicionarioDeDados.URL_TODOS_IMAGE.getInformacao() + strurl);
			InputStream is = (InputStream) url.getContent();
			byte[] buffer = new byte[8192];
			int bytesRead;
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			while ((bytesRead = is.read(buffer)) != -1) {
				output.write(buffer, 0, bytesRead);
			}
			image = output.toByteArray();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			image = null;
		} catch (IOException e) {
			e.printStackTrace();
			image = null;
		}

		return image;
	}
	
}
